import { baseURL } from './config'
var log = require('./log') // 引用上面的log.js文件
log.info('hello test hahaha')
const request = (url, options) => {
  let token = wx.getStorageSync('token');
  options.url = url
  return new Promise((resolve, reject) => {
    options.isLoading && wx.showLoading({
      title: '',
  })
    wx.request({
      url: `${baseURL}${url}`,
      method: options.method,
      data: options.data,
      header: {
        'content-type': options.json ? 'application/json' : 'application/x-www-form-urlencoded',
        Authorization: token || ''
      },
      success(response) {
        const res = response.data
        const { code, message } = res
        options.isLoading && wx.hideLoading()
        if (code !== '0') {
          // 表示是报错了
          console.log('msg:', message, 'url:', url, 'Authorization:', token)
        }
        if (code === undefined) {
          // 客服那边接口返回的未按照规则，直接返回的
          resolve(res)
        } else if (code === '0' || code === 65523 || code === 65522 || code === 2001) {
          resolve(res)
        } else if (code == 5003) {
          console.log('5003')
          wx.showToast({
            title: message || `code:${code}`,
            icon: 'none',
            duration: 2000
          })
          console.log('request---a');
          wx.setStorageSync('islogin', 0);
          getApp().globalData.userInfo = null;
          getApp().globalData.token = null;
          getApp().globalData.applyId = null;
          getApp().globalData.sceneMain = null;
          getApp().globalData.sceneQuery = null;
          getApp().globalData.um_uuid = null;
          getApp().globalData.scene = null;
          getApp().globalData.employ = false;
          wx.clearStorageSync();
          getApp().login()
        }else if(code==5006){
          resolve(res)
        }else if(code==1000){
          resolve(res)
        }  else {
          wx.showToast({
            title: message || `code:${code}`,
            icon: 'none',
            duration: 2000
          })
          resolve(res)
        }
      },
      fail(error) {
          reject(error.data)
      }
    })
  })
}
const upload = (url,filePath,name,header,key,ossConfig,isLoading) =>{
  return new Promise((resolve, reject)=> {
      isLoading && wx.showLoading({
          title: '上传中',
      })

      console.log('ossConfig=---ossConfig',url,filePath,name,key,ossConfig)
      wx.uploadFile({
          url: ossConfig.host,
          filePath,
          name,
          header,
          formData: {
            key: key,
            policy: ossConfig.policy,
            OSSAccessKeyId: ossConfig.accessId,
            signature: ossConfig.signature,
            success_action_status : '200', //让服务端返回200,不然，默认会返回204
        },
       success:(res)=> {
            console.log(res, 'resss')
            resolve(res)
            isLoading && wx.hideLoading();
          },
          fail:(error)=>{
              reject(error)
              wx.showToast({
                title: '上传失败，请重新上传',
              })
          },
          complete: () => {
              // setTimeout(() => {
              //     isLoading && wx.hideLoading();
              // }, 200);
          }
        });
  })
}

const get = (url, options = {}, isToLogin = true, isLoading = true) => {
  return request(url, { method: 'GET', data: options, isToLogin, isLoading })
}

// post参数
const post = (url, options, json = false, isToLogin = true, isLoading = false) => {
  log.info('post:', '接口路径:', url, '传参对象:', options.data);
  return request(url, { method: 'POST', data: options, json, isToLogin, isLoading })
}

const put = (url, options, json = false, isToLogin = true, isLoading = true) => {
  return request(url, { method: 'PUT', data: options, json: json, isToLogin, isLoading })
}

// 不能声明DELETE（关键字）
const remove = (url, options) => {
  return request(url, { method: 'DELETE', data: options })
}

const uploadFile = ({url='/api/oss-files-service/cn.askdr.ossfiles.service.FileService/upload',filePath,name,header,key,ossConfig,isLoading=true}) =>{
  return upload(url, filePath,name,header,key,ossConfig,isLoading)
}

const http = {
  get,
  post,
  put,
  remove,
  uploadFile,

}
export { http }
